package north

import (
	"errors"
	"fmt"
	"iot-base/common/cache"
	"iot-base/common/ctrltype"
	"iot-base/common/notify"
	"strings"
	"time"
)

func init() {
	RegisterCtrlFun("doRTSPPush", func(pCmd *ctrltype.CtrlCmd) (map[string]interface{}, error) {
		fmt.Println("----------------doRtspPush------on dm to run-----")
		if pCmd.Params == nil {
			fmt.Println("error--------doRTSPUSH-------------1")
			return nil, errors.New("param missed")
		}
		src := pCmd.Params["srcurl"]
		if src != nil {
			ssrc := src.(string)
			parts := strings.Split(ssrc, ":::")
			if len(parts) >= 2 {
				var vid = parts[0]
				var vtoken = parts[1]
				info, err := cache.GetVideoAddr(vid)
				if err == nil && info != nil {
					var found = false
					if info != nil && err == nil {
						for _, option := range info.StreamOptions {
							//if option != nil {
							if option.Name == vtoken {
								fmt.Println("found ------------token", option.RawAddr)
								pCmd.Params["srcurl"] = option.RawAddr
								if option.RawAddr == "" {
									fmt.Println("error--------doRTSPUSH-------------2")
									return nil, errors.New("no token found")
								}
								found = true
								break
							}
							//}
						}
					}
					slen := len(info.StreamOptions)
					if !found && slen > 0 {
						pCmd.Params["srcurl"] = info.StreamOptions[0].RawAddr
						fmt.Println("set default---------", info.StreamOptions[0].RawAddr)
					}
					pCmd.ThingID = info.DispatchID
					fmt.Println("ctrl-------------thingid", pCmd.ThingID)

					var pCtrlResult *ctrltype.CtrlResult
					notify.Ctrl(pCmd, 2*time.Second, func(pResult *ctrltype.CtrlResult) {
						pCtrlResult = pResult
					}, true)
					if pCtrlResult != nil {
						return pCtrlResult.Result, pCtrlResult.Error
					}
				}
				fmt.Println("error--------doRTSPUSH-------GetVideoAddr------4", err)

				return nil, err

			}
		}
		fmt.Println("error--------doRTSPUSH-------------3")
		return nil, errors.New("param missed")
	})
}
